<?php

namespace App\Backend\Http\Ql;

use QL\QueryList;

class CircleQueryService {
    protected $client;
    protected $ql;

    /**
     * 模拟登录discuz
     * CircleQueryService constructor.
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function __construct() {
        $this->ql = QueryList::getInstance();
        $this->client = $this->client();
    }

    public function article($url) {
        //内容规则
        $comment_rule = [
//            'avatar' => ['#postlist>div .deanw1260:eq(0) .deanwavar>a>img', 'src'], //用户头像
//            'nick_name' => ['#postlist>div .deanw1260:eq(0) .deanwinfoso>h3', 'text'], //用户名
            'title' => ['#postlist>div .deanw1260:eq(0) .deanwright>h3', 'text'], //标题
            'content' => ['#postlist>div .plhin .pcb>.t_fsz>table>tr>td', 'html'], //详情
        ];
        $response = $this->client->request('GET', $url);
        $html = (string) $response->getBody();
        $data = $this->ql->html($html)->removeHead()->encoding('UTF-8', 'GB2312')->rules($comment_rule)->query()->getData()[0];
        unset($html);
        unset($comment_rule);
        $this->ql->destruct();
        return $data;
    }

    /**
     * 模拟登录 返回登录后的cookie
     * @return \GuzzleHttp\Client
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function client() {
        $loginurl = 'http://www.tuozhe8.com/member.php?mod=logging&action=login';
        $client = new \GuzzleHttp\Client(['cookies' => true]);
        //获取登录cookie
        $response = $client->request('GET', $loginurl);
        //获取到页面源码
        $body = $response->getBody();
        $html = (string) $body;
        $html = $this->ql->html($html);
        $form = $html->find('form')->eq(1);
        $form->find('input[name=username]')->val('@qwertyuiop@');
        $form->find('input[name=password]')->val('1zxcvbnm');
        //序列化表单数据
        $fromData = $form->serializeArray();
        $postData = [];
        foreach ($fromData as $item) {
            $postData[$item['name']] = $item['value'];
        }
        $postData['loginfield'] = 'username';
        $postData['loginsubmit'] = 'yes';
        $postData['username'] = '@qwertyuiop@';
        $client->request('POST', $loginurl, ['form_params' => $postData]); //post模拟登录
        return $client;
    }

}